<?php

namespace App\Models;

use App\Handlers\MaterialHandler;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class GoodsSkuToMaterial extends Model
{
	protected $fillable = [
		'goods_sku_id',
		'material_id',
		'number'
	];
	
	public function material()
	{
		return $this->belongsTo(Materials::class);
	}
		
	// 改变库存 生成记录
	public static function reduce($stock = [], $needs = [],int $store_id,$type = 1)
	{
		if (empty($stock) || empty($needs)) {
			return true;
		}
		foreach ($needs as $k => $v) {
		    if ($type == 1){ //type为1：下单时材料库存的减少
                $reduceStock = MaterialHandler::deduction_stock($stock[$k], $v);
                $description = "订单商品购买";
                $style = 2;
                $status = 2;
            }else if ($type == 2){ //订单取消/退款时，材料库存返回
                $reduceStock = MaterialHandler::return_stock($stock[$k], $v);
		        $description = "订单商品取消/退款";
		        $style = 1;
		        $status = 1;
            }
		    
			foreach ($reduceStock as $key => $value) {
				// 减少库存
				static $pToMaterial = [];
				$pToMaterial[] = [
					'id' => $value['id'],
					'stock' => $value['stock'],
					'sell' => $value['sell'],
					'status' => $value['status']
				];
				// 生成消耗记录
				static $record = [];
				$record[] = [
					'store_id' => $store_id,
					'purchase_to_material_id' => $value['id'],
					'material_id' => $k,
					'number' => $v,
					'description' => $description,
					'style' => $style,
					'type' => $status,
					'created_at' => Carbon::now(),
					'updated_at' => Carbon::now()
				];
			}
		}
		// 批量更新
		 $purchaseupdate = PurchaseToMaterial::updateBatch('purchase_to_materials', $pToMaterial);
        // 批量插入
		$reduce = DB::table('record_materials')->insert($record);

		if ($reduce && $purchaseupdate){
		    return true;
        }else{
            return false;
        }
	}
}
